<template>
  <div ref="pressureChart" class="pressure-chart"></div>
</template>

<script>
import * as d3 from "d3";
import { io } from "socket.io-client";

export default {
  data() {
    return {
      socket: null,
      positions: [
        { x: 10, y: 11 },
        { x: 8.5, y: 23 },
        { x: 22.5, y: 26.8 },
        { x: 15.5, y: 60 }
      ]
    };
  },
  mounted() {
    // 初始化WebSocket连接
    this.socket = io("http://127.0.0.1:5000");

    this.socket.on("rightInsole_data_event", (data) => {
      if (data && data.data) {
        const pressureString = data.data; // 获取字符串数据
        const pressureValues = pressureString.split(' ').slice(-4).map(Number); // 提取最后四个压力值
        this.updateChart(pressureValues);
      } else {
        console.error("Received malformed data:", data);
      }
    });

    // 初始化图表
    this.initChart();
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.disconnect();
    }
  },
  methods: {
    initChart() {
      const svg = d3.select(this.$refs.pressureChart)
        .append("svg")
        .attr("width", 300)
        .attr("height", 700);

      this.positions.forEach((position, i) => {
        svg.append("circle")
          .attr("cx", position.x * 10)
          .attr("cy", position.y * 10)
          .attr("r", 10)
          .attr("fill", "red")
          .attr("opacity", 0.5)
          .attr("id", `circle-${i}`);
      });
    },
    updateChart(pressures) {
      const svg = d3.select(this.$refs.pressureChart).select("svg");

      pressures.forEach((pressure, i) => {
        const radius = Math.log2((pressure + 1) * 1000);
        const colorScale = d3.scaleLinear()
          .domain([0, d3.max(pressures)])
          .range(["lightcoral", "darkred"]);

        svg.select(`#circle-${i}`)
          .transition()
          .duration(200)
          .attr("r", radius)
          .attr("fill", colorScale(pressure));
      });

    }
  }
};
</script>

<style scoped>
.pressure-chart {
  width: 300px;
  height: 700px;
  /*引用assets目录下的2.jpg */
  background-image: url('@/assets/2.jpg');
  background-size: cover;
}
</style>




